package com.boco.fznq.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.Interpolator;
import android.widget.Scroller;

import com.culiu.core.utils.debug.DebugLog;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;

/**
 * @describe 专为Banner的ViewPager而存在.
 * @author wangheng
 * @date: 2014年12月3日 下午8:22:06 <br/>
 */
public class BannerViewPager extends ViewPager {

    /** 自动滚动的时候需要发的消息 **/
    private static final int HANDLE_AUTO_SCROLL = 0x1001;

    /** 手指是否停留在ViewPager上 **/
    private boolean isTouched = false;

    /** 手指按下的X轴坐标 **/
    private float downX;

    /** 手指按下的Y轴坐标 **/
    private float downY;

    /** 为了控制自动滚动速度，而自定义的Scroller **/
    private CustomScroller scroller;

    /** 自动滚动的时间间隔，默认是5000毫秒 **/
    private long autoScrollInterval = 5000;

    /** 滚动到下一页需要的时间 **/
    private int mDuration = 750;

    /** 是否可以自动滚动 **/
    private boolean isAutoScrollable = false;

    private String mStirng;

    /** 自动滚动的Handler信息 **/
    private AutoScrollHandler mHandler = new AutoScrollHandler(this);

    public BannerViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public BannerViewPager(Context context) {
        super(context);
        init(context, null);
    }

    /**
     * updateChatOption:初始化ViewPager. <br/>
     * @author wangheng
     * @param context
     * @param attrs
     */
    private void init(Context context, AttributeSet attrs) {
        setViewPagerScroller();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        int action = ev.getAction();

        if(action == MotionEvent.ACTION_DOWN) {
            isTouched = true;
            stopAutoScrollInternal();
        } else if(action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            isTouched = false;
            startAutoScrollInternal();
        }

        // 解决品牌团viewpager嵌套viewpager的事件传递问题 lxh
        switch(ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = getSecureX(ev);
                downY = getSecureY(ev);
                getParent().getParent().requestDisallowInterceptTouchEvent(true);
                requestFocus();
                break;
            case MotionEvent.ACTION_MOVE:
                float moveX = getSecureX(ev);
                float moveY = getSecureY(ev);
                if(Math.abs(moveX - downX) > Math.abs(moveY - downY)) {
                    getParent().getParent().requestDisallowInterceptTouchEvent(true);
                } else {
                    getParent().getParent().requestDisallowInterceptTouchEvent(false);
                }

                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                getParent().getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }
        try {
            return super.dispatchTouchEvent(ev);
        } catch(Throwable e) {
            DebugLog.e(String.valueOf(e.getMessage()));
        }
        return false;
    }

    /**
     * 采用静态内部类进行处理内存泄漏的问题
     * @describe TODO 类描述信息(可选).
     * @author wangheng
     * @date: 2015年1月22日 下午3:56:36 <br/>
     */
     static class AutoScrollHandler extends Handler {
        /**
         * 解决内存泄漏，采用弱引用处理
         */
        WeakReference<BannerViewPager> mBannerViewPager;

        AutoScrollHandler(BannerViewPager bannerViewPager) {
            mBannerViewPager = new WeakReference<BannerViewPager>(bannerViewPager);
        }

        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case HANDLE_AUTO_SCROLL:
                    BannerViewPager bannerViewPager = mBannerViewPager.get();
                    if (bannerViewPager != null) {
                        bannerViewPager.autoScroll();
                    }
                    break;

                default:
                    break;
            }
        }
    }

    /**
     * setAutoScrollInterval:设置切换页面的时间. <br/>
     * @author wangheng
     * @param autoScrollIntervalByMillis
     */
    public void setAutoScrollInterval(long autoScrollIntervalByMillis) {
        this.autoScrollInterval = autoScrollIntervalByMillis;
    }

    /**
     * setScrollDuration:设置切换页面锁使用的时间，单位毫秒. <br/>
     * @author wangheng
     * @param scrollDuration
     */
    public void setScrollDuration(int scrollDuration) {
        this.mDuration = scrollDuration;
    }

    /**
     * startAutoScroll:开始自动滚动. <br/>
     * @author wangheng
     */
    public void startAutoScroll() {
        isAutoScrollable = true;
        startAutoScrollInternal();
    }

    /**
     * startAutoScrollInternal:开始自动滚动，但是不会设置标记位(开始滚动之前先干掉原来的滚动信息). <br/>
     * @author wangheng
     */
    private void startAutoScrollInternal() {
        if(isAutoScrollable) {
            stopAutoScrollInternal();
            mHandler.sendEmptyMessageDelayed(HANDLE_AUTO_SCROLL, autoScrollInterval);
        }
    }

    /**
     * stopAutoScroll:停止滚动，状态不会恢复，除非重新调用startAutoScroll()方法. <br/>
     * @author wangheng
     */
    public void stopAutoScroll() {
        isAutoScrollable = false;
        stopAutoScrollInternal();
    }

    /**
     * stopAutoScrollInternal:停止自动滚动，但是不会设置状态，当手指离开屏幕，可以自动恢复. <br/>
     * @author wangheng
     */
    private void stopAutoScrollInternal() {
        mHandler.removeMessages(HANDLE_AUTO_SCROLL);
    }

    /**
     * autoScroll:自动滚动到下一页或者第0页. <br/>
     * @author wangheng
     */
    private void autoScroll() {
        if(getAdapter() == null || getAdapter().getCount() <= 1 || ! isAutoScrollable) {
            return;
        }
        /*
         * try { int[] screen = new int[2]; getLocationOnScreen(screen); Rect local = new Rect(); getLocalVisibleRect(local);
         * DebugLog.e("wangheng", getTop() + "------------\nscreen:" + screen[0] + "," + screen[1] + "\nlocal:" + local);
         * if(screen[1] < 0 && local.top == 0) { mHandler.sendEmptyMessageDelayed(HANDLE_AUTO_SCROLL, autoScrollInterval); return; }
         * } catch(Exception e) { DebugLog.e(String.valueOf(e.getMessage())); }
         */

        int current = getCurrentItem();
        int count = getAdapter().getCount();
        if(current >= 0 && current < count - 1) {
            setCurrentItem(current + 1);
        } else {
            setCurrentItem(0);
        }

        mHandler.sendEmptyMessageDelayed(HANDLE_AUTO_SCROLL, autoScrollInterval);
    }

    /**
     * isTouched:ViewPager是否正在被触摸. <br/>
     * @author wangheng
     * @return
     */
    public boolean isTouched() {
        return isTouched;
    }

    /**
     * setViewPagerScroller:设置自定义的Scroller. <br/>
     * @author wangheng
     */
    private void setViewPagerScroller() {
        try {
            Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
            scrollerField.setAccessible(true);
            Field interpolatorField = ViewPager.class.getDeclaredField("sInterpolator");
            interpolatorField.setAccessible(true);

            scroller = new CustomScroller(getContext(), (Interpolator)interpolatorField.get(null));
            scrollerField.set(this, scroller);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @describe 自定义Scroller.
     * @author wangheng
     * @date: 2015年1月22日 下午3:55:19 <br/>
     */
    class CustomScroller extends Scroller {

        public CustomScroller(Context context) {
            super(context);
        }

        public CustomScroller(Context context, Interpolator interpolator) {
            super(context, interpolator);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {
            startScroll(startX, startY, dx, dy, mDuration);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }
    }

    /**
     * getSecureX:安全的得到MotionEvent中的x,得到失败返回0. <br/>
     * @author wangheng
     * @param ev
     * @return
     */
    private float getSecureX(MotionEvent ev) {
        try {
            return ev.getX();
        } catch(Throwable e) {
            DebugLog.e(String.valueOf(e.getMessage()));
        }
        return 0;
    }

    /**
     * getSecureY:安全的得到MotionEvent中的Y,得到失败返回0. <br/>
     * @author wangheng
     * @param ev
     * @return
     */
    private float getSecureY(MotionEvent ev) {
        try {
            return ev.getY();
        } catch(Throwable e) {
            DebugLog.e(String.valueOf(e.getMessage()));
        }
        return 0;
    }

    @Override
    protected void onAttachedToWindow() {//bug1143
        super.onAttachedToWindow();

        try {
            Field firstLayout = ViewPager.class.getDeclaredField("mFirstLayout");
            firstLayout.setAccessible(true);
            firstLayout.set(this, false);
        } catch (Exception e) {
            DebugLog.e(e.toString());
        }
    }
}
